package bidgetserver;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//this servlet send all the reminders of a given user back to the client in JSON format.
public class SendSearchReminderToClient extends HttpServlet{
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		String userName = req.getParameter("UserName");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from "+Reminder.class.getName()+" where userName == '"+userName +"'";


		List<Reminder> searchReminders = (List<Reminder>) pm.newQuery(query).execute();

		if (searchReminders.isEmpty()){
			resp.getWriter().printf("");
		} else {
			String response = "{\"search\" : [";
			for (Reminder r : searchReminders){
				response += " \""+r.getSearchString()+"\",";
			}
			response = response.substring(0, response.length()-1);
			response +=" ], ";

			response += "\"results\" : [";
			for (Reminder r : searchReminders){
				response += " ["+r.getTop5Results()+"],";
			}
			response = response.substring(0, response.length()-1);
			response +=" ], ";


			response += "\"high\" : [";
			for (Reminder r : searchReminders){
				response += " \""+r.getMaxPrice()+"\",";
			}
			response = response.substring(0, response.length()-1);
			response +=" ], ";

			response += "\"low\" : [";
			for (Reminder r : searchReminders){
				response += " \""+r.getMinPrice()+"\",";
			}
			response = response.substring(0, response.length()-1);
			response +=" ], ";

			response += "\"ID\" : [";
			for (Reminder r : searchReminders){
				response += " \""+r.getReminderID()+"\",";
			}
			response = response.substring(0, response.length()-1);
			response+=" ]}";

			resp.getWriter().print(response);
		}
	}
}
